﻿from odoo import models, fields, api, _
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import logging
from odoo.exceptions import UserError
import datetime

logger = logging.getLogger(__name__)


class Team(models.Model):
    _name = 'team.info'
    _description = 'The information of some teams'

    name = fields.Char(
        '项目组名称',
        required=True
    )
    person_in_charge = fields.Many2one(
        'person.info',
        string='项目负责人',
        required=True,
        domain=[('title.name', '!=', '组员')]
    )
    person_in_charge_rule = fields.Many2one(
        'res.users',
        string='项目负责人',
        required=True,
        compute='_change_rule'
    )
    personnel = fields.Many2many(
        'person.info',
        string='项目组人员'
    )
    personnel_rule = fields.Many2many(
        'res.users',
        string='项目组人员',
        compute='_change_rule_person'
    )
    history_projects = fields.One2many(
        'project.project',
        'team',
        string='历史承包项目'
    )
    status = fields.Selection(
        [(1, '项目组筹备阶段'),
         (2, '项目组活跃阶段'),
         (3, '项目组冬眠阶段')],
        string='项目组状态',
        default=1
    )
    establish_time = fields.Date(
        '成立时间',
        required=True,
        default=lambda self: fields.Date.today(),
        track_visibility='onchange'
    )
    age = fields.Char(
        '项目组年龄'
    )
    end_date = fields.Date(
        '冬眠时间'
    )

    @api.one
    @api.depends('person_in_charge')
    def _change_rule(self):
        if self.person_in_charge_rule.name is False:
            new_person_in_charge_rule = self.env['res.users'].search(
                [('name', '=', self.person_in_charge.name)])
            self.person_in_charge_rule = new_person_in_charge_rule

        elif self.person_in_charge_rule.name != self.person_in_charge.name:
            new_person_in_charge_rule = self.person_in_charge_rule.search(
                [(self.person_in_charge_rule.name, '=', self.person_in_charge.name)])
            self.person_in_charge_rule = new_person_in_charge_rule

    @api.one
    @api.depends('personnel')
    def _change_rule_person(self):
        new_personnel_rule = self.env['res.users'].search(
            # [('name', '=', self.personnel.name)])
            [('login', '=', self.personnel.email)])
        self.personnel_rule += new_personnel_rule

    @api.one
    def call_set_up(self, person):
        sender = 'zilouis@qq.com'
        passwd = 'sovlbfcttwogbhhi'
        logger.info("Here is the person: %s", person)
        receiver = person.email  # 接收邮件，可设置为你的QQ邮箱或者其他邮箱
        mail_msg = """
                        <!doctype html>
                        <html>
                          <head>
                            <meta name="viewport" content="width=device-width">
                            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
                          </head>
                          <body class="" style="background-color: #f6f6f6; font-family: sans-serif; -webkit-font-smoothing: antialiased; font-size: 14px; line-height: 1.4; margin: 0; padding: 0; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;">
                            <table border="0" cellpadding="0" cellspacing="0" class="body" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%; background-color: #f6f6f6;">
                              <tr>
                                <td style="font-family: sans-serif; font-size: 14px; vertical-align: top;">&nbsp;</td>
                                <td class="container" style="font-family: sans-serif; font-size: 14px; vertical-align: top; display: block; Margin: 0 auto; max-width: 580px; padding: 10px; width: 580px;">
                                  <div class="content" style="box-sizing: border-box; display: block; Margin: 0 auto; max-width: 580px; padding: 10px;">

                                    <!-- START CENTERED WHITE CONTAINER -->
                                    <span class="preheader" style="color: transparent; display: none; height: 0; max-height: 0; max-width: 0; opacity: 0; overflow: hidden; mso-hide: all; visibility: hidden; width: 0;">This is preheader text. Some clients will show this text as a preview.</span>
                                    <table class="main" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%; background: #ffffff; border-radius: 3px;">

                                      <!-- START MAIN CONTENT AREA -->
                                      <tr>
                                        <td class="wrapper" style="font-family: sans-serif; font-size: 14px; vertical-align: top; box-sizing: border-box; padding: 20px;">
                                          <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%;">
                                            <tr>
                                              <td style="font-family: sans-serif; font-size: 14px; vertical-align: top;">
                                                <p style="font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;">尊敬的{person_name},</p>
                                                <p style="font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;">您所属的项目组{team},已成立,项目负责人为{leader},希望您在日后的生活和工作中能够成功融入到{team}的大家庭中！</p>
                                                <table border="0" cellpadding="0" cellspacing="0" class="btn btn-primary" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%; box-sizing: border-box;">
                                                  <tbody>
                                                    <tr>
                                                      <td align="left" style="font-family: sans-serif; font-size: 14px; vertical-align: top; padding-bottom: 15px;">
                                                        <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: auto;">
                                                          <tbody>
                                                            <tr>
                                                              <td style="font-family: sans-serif; font-size: 14px; vertical-align: top; background-color: #3498db; border-radius: 5px; text-align: center;"> <a href="http://admin.hubusugon.cn" target="_blank" style="display: inline-block; color: #ffffff; background-color: #3498db; border: solid 1px #3498db; border-radius: 5px; box-sizing: border-box; cursor: pointer; text-decoration: none; font-size: 14px; font-weight: bold; margin: 0; padding: 12px 25px; text-transform: capitalize; border-color: #3498db;">湖北大学瑞翼工坊内部管理系统</a> </td>
                                                            </tr>
                                                          </tbody>
                                                        </table>
                                                      </td>
                                                    </tr>
                                                  </tbody>
                                                </table>
                                                <p style="font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;">祝您生活愉快！</p>
                                              </td>
                                            </tr>
                                          </table>
                                        </td>
                                      </tr>

                                    <!-- END MAIN CONTENT AREA -->
                                    </table>

                                    <!-- START FOOTER -->
                                    <div class="footer" style="clear: both; Margin-top: 10px; text-align: center; width: 100%;">
                                      <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%;">
                                        <tr>
                                          <td class="content-block" style="font-family: sans-serif; vertical-align: top; padding-bottom: 10px; padding-top: 10px; font-size: 12px; color: #999999; text-align: center;">
                                            <span class="apple-link" style="color: #999999; font-size: 12px; text-align: center;">版权所有©湖北大学瑞翼工坊</span>
                                          </td>
                                        </tr>

                                      </table>
                                    </div>
                                    <!-- END FOOTER -->

                                  <!-- END CENTERED WHITE CONTAINER -->
                                  </div>
                                </td>
                                <td style="font-family: sans-serif; font-size: 14px; vertical-align: top;">&nbsp;</td>
                              </tr>
                            </table>
                          </body>
                        </html>
                    """.format(person_name=person.name, team=self.name, leader=self.person_in_charge.name)
        message = MIMEText(mail_msg, 'html', 'utf-8')
        message['From'] = Header("湖北大学瑞翼工坊", 'utf-8')
        message['To'] = Header(person.name, 'utf-8')

        subject = '湖北大学瑞翼工坊'
        message['Subject'] = Header(subject, 'utf-8')

        try:
            smtpObj = smtplib.SMTP_SSL("smtp.qq.com", 465)
            smtpObj.login(sender, passwd)
            smtpObj.sendmail(sender, receiver, message.as_string())
            print("邮件发送成功")
        except Exception as e:
            raise UserError(_('邮件未发送成为!原因如下:%s') % e)

    @api.one
    def establish(self):
        for email in self.personnel:
            self.call_set_up(email)
        self.status = 2

    @api.one
    def call_sleep(self, person):
        sender = 'zilouis@qq.com'
        passwd = 'sovlbfcttwogbhhi'
        logger.info("Here is the person: %s", person)
        receiver = person.email  # 接收邮件，可设置为你的QQ邮箱或者其他邮箱
        mail_msg = """
                            <!doctype html>
                            <html>
                              <head>
                                <meta name="viewport" content="width=device-width">
                                <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
                              </head>
                              <body class="" style="background-color: #f6f6f6; font-family: sans-serif; -webkit-font-smoothing: antialiased; font-size: 14px; line-height: 1.4; margin: 0; padding: 0; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;">
                                <table border="0" cellpadding="0" cellspacing="0" class="body" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%; background-color: #f6f6f6;">
                                  <tr>
                                    <td style="font-family: sans-serif; font-size: 14px; vertical-align: top;">&nbsp;</td>
                                    <td class="container" style="font-family: sans-serif; font-size: 14px; vertical-align: top; display: block; Margin: 0 auto; max-width: 580px; padding: 10px; width: 580px;">
                                      <div class="content" style="box-sizing: border-box; display: block; Margin: 0 auto; max-width: 580px; padding: 10px;">

                                        <!-- START CENTERED WHITE CONTAINER -->
                                        <span class="preheader" style="color: transparent; display: none; height: 0; max-height: 0; max-width: 0; opacity: 0; overflow: hidden; mso-hide: all; visibility: hidden; width: 0;">This is preheader text. Some clients will show this text as a preview.</span>
                                        <table class="main" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%; background: #ffffff; border-radius: 3px;">

                                          <!-- START MAIN CONTENT AREA -->
                                          <tr>
                                            <td class="wrapper" style="font-family: sans-serif; font-size: 14px; vertical-align: top; box-sizing: border-box; padding: 20px;">
                                              <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%;">
                                                <tr>
                                                  <td style="font-family: sans-serif; font-size: 14px; vertical-align: top;">
                                                    <p style="font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;">尊敬的{person_name},</p>
                                                    <p style="font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;">您所属的项目组{team},已正式进入冬眠状态,感谢您{age}天的辛勤付出与陪伴！</p>
                                                    <table border="0" cellpadding="0" cellspacing="0" class="btn btn-primary" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%; box-sizing: border-box;">
                                                      <tbody>
                                                        <tr>
                                                          <td align="left" style="font-family: sans-serif; font-size: 14px; vertical-align: top; padding-bottom: 15px;">
                                                            <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: auto;">
                                                              <tbody>
                                                                <tr>
                                                                  <td style="font-family: sans-serif; font-size: 14px; vertical-align: top; background-color: #3498db; border-radius: 5px; text-align: center;"> <a href="http://admin.hubusugon.cn" target="_blank" style="display: inline-block; color: #ffffff; background-color: #3498db; border: solid 1px #3498db; border-radius: 5px; box-sizing: border-box; cursor: pointer; text-decoration: none; font-size: 14px; font-weight: bold; margin: 0; padding: 12px 25px; text-transform: capitalize; border-color: #3498db;">湖北大学瑞翼工坊内部管理系统</a> </td>
                                                                </tr>
                                                              </tbody>
                                                            </table>
                                                          </td>
                                                        </tr>
                                                      </tbody>
                                                    </table>
                                                    <p style="font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;">祝您生活愉快！</p>
                                                  </td>
                                                </tr>
                                              </table>
                                            </td>
                                          </tr>

                                        <!-- END MAIN CONTENT AREA -->
                                        </table>

                                        <!-- START FOOTER -->
                                        <div class="footer" style="clear: both; Margin-top: 10px; text-align: center; width: 100%;">
                                          <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%;">
                                            <tr>
                                              <td class="content-block" style="font-family: sans-serif; vertical-align: top; padding-bottom: 10px; padding-top: 10px; font-size: 12px; color: #999999; text-align: center;">
                                                <span class="apple-link" style="color: #999999; font-size: 12px; text-align: center;">版权所有©湖北大学瑞翼工坊</span>
                                              </td>
                                            </tr>

                                          </table>
                                        </div>
                                        <!-- END FOOTER -->

                                      <!-- END CENTERED WHITE CONTAINER -->
                                      </div>
                                    </td>
                                    <td style="font-family: sans-serif; font-size: 14px; vertical-align: top;">&nbsp;</td>
                                  </tr>
                                </table>
                              </body>
                            </html>
                        """.format(person_name=person.name, team=self.name, leader=self.person_in_charge.name,
                                   age=self.age)
        message = MIMEText(mail_msg, 'html', 'utf-8')
        message['From'] = Header("湖北大学瑞翼工坊", 'utf-8')
        message['To'] = Header(person.name, 'utf-8')

        subject = '湖北大学瑞翼工坊'
        message['Subject'] = Header(subject, 'utf-8')

        try:
            smtpObj = smtplib.SMTP_SSL("smtp.qq.com", 465)
            smtpObj.login(sender, passwd)
            smtpObj.sendmail(sender, receiver, message.as_string())
            print("邮件发送成功")
        except Exception as e:
            raise UserError(_('邮件未发送成为!原因如下:%s') % e)

    def sleep(self):
        start_date = self.establish_time
        curr_date = datetime.datetime.now().strftime('%Y-%m-%d')
        curr_date = datetime.datetime.strptime(curr_date, "%Y-%m-%d")
        curr_date = datetime.datetime.date(curr_date)
        self.age = (start_date - curr_date).days
        self.end_date = fields.Date.today()
        for email in self.personnel:
            self.call_sleep(email)
        self.status = 3
